package com.cyou.qb.face.util.converter;

/* 
 * HttpRequestProxy.java 
 * 
 * Created on November 3, 2008, 9:53 AM 
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.cyou.qb.face.constants.FaceConstants;
import com.cyou.qb.face.exception.QbGetDataException;

/**
 * 
 * @author bird email:lihongfu-84@163.com
 * 
 *         2008-11-4 09:49:48
 */
@SuppressWarnings("unused")
public class FaceHttpUtil {
	// 超时间隔
	private static int connectTimeOut = 60000;
	// 让connectionmanager管理httpclientconnection时是否关闭连接
	private static boolean alwaysClose = false;
	// 返回数据编码格式
	private String encoding = "UTF-8";
	/**
	 * Log日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(FaceHttpUtil.class);
	
	/**
	 * 用法： FaceHttpUtil hrp = new FaceHttpUtil();
	 * hrp.doRequest("http://www.163.com",null,null,"gbk");
	 * 
	 * @param url
	 *            请求的资源ＵＲＬ
	 * @param postData
	 *            POST请求时form表单封装的数据 没有时传null
	 * @param header
	 *            request请求时附带的头信息(header) 没有时传null
	 * @param encoding
	 *            response返回的信息编码格式 没有时传null
	 * @return response返回的文本数据
	 * @throws Exception 
	 */
	public static String doRequest(String url, Map<?, ?> postData, Map<?, ?> header,String encoding) throws Exception {
		HttpClient client = new HttpClient(new SimpleHttpConnectionManager(alwaysClose));
		client.getHttpConnectionManager().getParams().setConnectionTimeout(FaceConstants.SERVICE_OF_173_TIME_OUT);
		client.getHttpConnectionManager().getParams().setSoTimeout(FaceConstants.SERVICE_OF_173_TIME_OUT);
		String responseString = null;
		// 头部请求信息
		Header[] headers = null;
		//设置超时时间
		if (header != null) {
			Set<?> entrySet = header.entrySet();
			int dataLength = entrySet.size();
			headers = new Header[dataLength];
			int i = 0;
			for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
				@SuppressWarnings("rawtypes")
				Map.Entry entry = (Map.Entry) itor.next();
				headers[i++] = new Header(entry.getKey().toString(), entry.getValue().toString());
			}
		}
		// post方式
		if (postData != null) {
			PostMethod postRequest = new PostMethod(url.trim());
			if (headers != null) {
				for (int i = 0; i < headers.length; i++) {
					postRequest.setRequestHeader(headers[i]);
				}
			}
			Set<?> entrySet = postData.entrySet();
			int dataLength = entrySet.size();
			NameValuePair[] params = new NameValuePair[dataLength];
			int i = 0;
			for (Iterator<?> itor = entrySet.iterator(); itor.hasNext();) {
				@SuppressWarnings("rawtypes")
				Map.Entry entry = (Map.Entry) itor.next();
				params[i++] = new NameValuePair(entry.getKey().toString(),entry.getValue().toString());
			}
			postRequest.setRequestBody(params);
			try {
				responseString = executeMethod(client,postRequest, encoding);
			} finally {
				postRequest.releaseConnection();
			}
		}
		// get方式
		if (postData == null) {
			GetMethod getRequest = new GetMethod(url.trim());
			if (headers != null) {
				for (int i = 0; i < headers.length; i++) {
					getRequest.setRequestHeader(headers[i]);
				}
			}
			try {
				responseString = executeMethod(client,getRequest, encoding);
			}finally {
				getRequest.releaseConnection();
			}
		}

		return responseString;
	}

	private static String executeMethod(HttpClient httpClient,HttpMethod request, String encoding)
			throws Exception {
		String responseContent = null;
		InputStream responseStream = null;
		BufferedReader rd = null;
		try {
			httpClient.executeMethod(request);
			if (encoding != null) {
				responseStream = request.getResponseBodyAsStream();
				rd = new BufferedReader(new InputStreamReader(responseStream,encoding));
				String tempLine = rd.readLine();
				StringBuffer tempStr = new StringBuffer();
				String crlf = System.getProperty("line.separator");
				while (tempLine != null) {
					tempStr.append(tempLine);
					tempStr.append(crlf);
					tempLine = rd.readLine();
				}
				responseContent = tempStr.toString();
			} else
				responseContent = request.getResponseBodyAsString();

			Header locationHeader = request.getResponseHeader("location");
			// 返回代码为302,301时，表示页面己经重定向，则重新请求location的url，这在
			// 一些登录授权取cookie时很重要
			if (locationHeader != null) {
				String redirectUrl = locationHeader.getValue();
				doRequest(redirectUrl, null, null, null);
			}
		} finally {
			if (rd != null)
				try {
					rd.close();
				} catch (IOException e) {
				}
			if (responseStream != null)
				try {
					responseStream.close();
				} catch (IOException e) {
				}
		}
		return responseContent;
	}

}